/**
* tab项公共组件
*/

'use strict'

var React=require('react-native')
var {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Animated,
  Dimensions,
  PropTypes,
}= React;

export default class TopTabBar extends React.Component{
  static propTypes={
    onValueChange:PropTypes.func,
    activeTab: PropTypes.number,
    tabs: PropTypes.array
  };

  constructor(props){
    super(props)

    this.state={
      scrollValue: new Animated.Value(this.props.initTab),
      activeTab:this.props.initTab,
    }
  }

  _onValueChange(tab,id){
    this.props.onValueChange(tab,id);
    this.setState({
      scrollValue: new Animated.Value(id),
      activeTab:id,
    })
  }

  _renderTabItem(tab,id){
    var tabLabelColor = id === this.state.activeTab?'#4ead7d':'gray';
    return (
      <TouchableOpacity key={id} onPress={this._onValueChange.bind(this,tab,id)}>
        <View style={styles.tabItem}>
          <Text style={[styles.tabLabel,{color:tabLabelColor}]}>{tab}</Text>
        </View>
      </TouchableOpacity>
    )
  }

  render(){
    var tabWidth=Dimensions.get('window').width;
    var tabUnderlineStyle = {
      position: 'absolute',
      width: tabWidth / this.props.tabs.length,
      height: 3,
      backgroundColor: '#4ead7d',
      bottom: 0,
    };

    var left = this.state.scrollValue.interpolate({
      inputRange: [0, 1],
      outputRange: [0, tabWidth / this.props.tabs.length]
    });

    return (
      <View style={styles.container}>
        {
          this.props.tabs.map((tab,i)=>this._renderTabItem(tab,i))
        }
        <Animated.View style={[tabUnderlineStyle, {left}]} />
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container:{
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center',
    height:30,
    marginBottom:5,
    marginTop:0,
    backgroundColor:'#fcf9f6'
  },
  tabItem:{

  },
  tabLabel:{
    color:'gray',
  }
});
